package com.javatip.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Utils {
    public static String getParentPath(String path, int levels) {
        if (levels <= 0) {
            return path;
        }
        int lastIndex = path.lastIndexOf("/");
        if (lastIndex == -1) {
            return path;
        }
        return getParentPath(path.substring(0, lastIndex), levels - 1);
    }

    public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
        // 创建目标文件的父目录，如果不存在则创建
        File targetFile = new File(targetFilePath);
        File parentDir = targetFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 开始文件复制操作
        try (FileInputStream fis = new FileInputStream(sourceFilePath);
             FileOutputStream fos = new FileOutputStream(targetFilePath)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        }
    }
}
